import React, { useRef, useEffect } from 'react';
import { Box, Typography, Grid, TextField, FormControlLabel, Checkbox, InputAdornment, MenuItem, GlobalStyles } from '@mui/material';
import HomeWorkIcon from '@mui/icons-material/HomeWork';
import BusinessIcon from '@mui/icons-material/Business';
import { STATES, COUNTRIES } from './Constants';

const PropertySection = ({ 
  formData, 
  handleChange, 
  errors, 
  textFieldStyle, 
  sectionHeaderStyle, 
  useSize,
  fullWidth = false // Default to false
}) => {
  const sectionRef = useRef(null);
  const fieldsRef = useRef({});

  // Register closest input detection by scroll position
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          // When an input is near center viewport, add the special class
          const input = entry.target;
          if (entry.isIntersecting) {
            // Only apply to inputs not already focused
            if (!input.classList.contains('field-focused')) {
              input.classList.add('field-centered');
            }
          } else {
            input.classList.remove('field-centered');
          }
        });
      },
      {
        // This configures it to trigger when field is near center of viewport
        root: null, // viewport
        rootMargin: '-40% 0px -40% 0px', // narrow band in middle of screen
        threshold: 0.1 // trigger with minimal visibility
      }
    );

    // Register all input wrappers with the observer
    const wrappers = sectionRef.current?.querySelectorAll('.field-wrapper');
    if (wrappers) {
      wrappers.forEach((wrapper) => observer.observe(wrapper));
    }

    return () => observer.disconnect();
  }, []);

  // Event handlers to manipulate DOM directly (no state changes)
  const registerField = (name) => {
    return (ref) => {
      if (ref) {
        fieldsRef.current[name] = ref;
        
        // Clear all style classes
        const resetClasses = () => {
          // Get the wrapper element
          const wrapper = ref.closest('.field-wrapper');
          if (!wrapper) return;
          
          document.querySelectorAll('.field-wrapper').forEach(el => {
            // Remove focused class from all other wrappers
            if (el !== wrapper && el.classList.contains('field-focused')) {
              el.classList.remove('field-focused');
            }
          });
          
          // Add focused class to this wrapper
          wrapper.classList.add('field-focused');
          // Remove centered class (focus overrides centering)
          wrapper.classList.remove('field-centered');
        };
        
        // The actual focus handler
        const handleFocus = () => {
          resetClasses();
        };
        
        // The blur handler (only remove focused if not going to another field)
        const handleBlur = (e) => {
          // Don't remove the focused class if moving to another of our fields
          const relatedTarget = e.relatedTarget;
          const stillInFields = relatedTarget && 
            relatedTarget.closest && 
            relatedTarget.closest('.field-wrapper');
            
          if (!stillInFields) {
            ref.closest('.field-wrapper')?.classList.remove('field-focused');
          }
        };
        
        // Add the event listeners directly to the input element
        // Find the actual input element inside the MUI TextField
        const inputElement = ref.querySelector('input, select');
        if (inputElement) {
          // Remove existing listeners to prevent duplicates
          inputElement.removeEventListener('focus', handleFocus);
          inputElement.removeEventListener('blur', handleBlur);
          
          // Add fresh listeners
          inputElement.addEventListener('focus', handleFocus);
          inputElement.addEventListener('blur', handleBlur);
        }
      }
    };
  };

  return (
    <Box ref={sectionRef}>
      {/* CSS-only approach using GlobalStyles */}
      <GlobalStyles styles={`
        /* Base field wrapper style */
        .field-wrapper {
          padding: 0;
          margin: 0;
          border-radius: 8px;
          transition: all 0.3s ease;
          box-shadow: none;
          width: 100%;
        }
        
        /* Field is in center of viewport */
        .field-wrapper.field-centered:not(.field-focused) {
          padding: 12px;
          margin: 8px 0;
          box-shadow: 0 4px 20px rgba(0,0,0,0.15);
          width: 100%;
        }
        
        /* Field has focus */
        .field-wrapper.field-focused {
          padding: 12px;
          margin: 8px 0;
          box-shadow: 0 4px 20px rgba(0,0,0,0.15);
          width: 100%;
        }
        
        /* Sizing for inputs in focused/centered fields */
        .field-wrapper.field-centered .MuiInputBase-root,
        .field-wrapper.field-focused .MuiInputBase-root {
          font-size: 1.1rem;
          padding: 4px 8px;
          width: 100%;
        }
        
        /* Background color for focused fields */
        .field-wrapper.field-focused .MuiInputBase-root {
          background-color: rgba(0,100,255,0.05);
        }
      `} />
      
      <Typography sx={sectionHeaderStyle}>
        <HomeWorkIcon sx={{ fontSize: '1rem', verticalAlign: 'middle', mr: 0.5, color: 'primary.main' }} />
        Property Information
      </Typography>
      
      <Grid 
        container 
        spacing={1}
        columns={12}
        sx={{ 
          width: '100%',
          margin: 0,
          padding: 0,
          display: 'flex',
          flexDirection: 'column'
        }}
      >
        <Grid item xs={12}>
          <FormControlLabel
            control={
              <Checkbox
                checked={formData.billEqualShip === 'Y'}
                onChange={handleChange}
                name="billEqualShip"
                color="primary"
                size={useSize}
              />
            }
            label={<Typography sx={{ fontSize: '0.8rem' }}>Property address is the same as owner address</Typography>}
          />
        </Grid>
        
        {formData.billEqualShip === 'N' && (
          <>
            <Grid item xs={12}>
              <Box className="field-wrapper" sx={{ width: '100%' }}>
                <TextField
                  {... (fullWidth ? { fullWidth: true } : {})}
                  label="Property Owner First Name"
                  name="cShipFname"
                  value={formData.cShipFname}
                  onChange={handleChange}
                  error={!!errors.cShipFname}
                  helperText={errors.cShipFname}
                  size={useSize}
                  sx={textFieldStyle}
                  ref={registerField('cShipFname')}
                  required
                />
              </Box>
            </Grid>
            <Grid item xs={12}>
              <Box className="field-wrapper" sx={{ width: '100%' }}>
                <TextField
                  {... (fullWidth ? { fullWidth: true } : {})}
                  label="Property Owner Last Name"
                  name="cShipLname"
                  value={formData.cShipLname}
                  onChange={handleChange}
                  error={!!errors.cShipLname}
                  helperText={errors.cShipLname}
                  size={useSize}
                  sx={textFieldStyle}
                  ref={registerField('cShipLname')}
                  required
                />
              </Box>
            </Grid>
            <Grid item xs={12}>
              <Box className="field-wrapper" sx={{ width: '100%' }}>
                <TextField
                  {... (fullWidth ? { fullWidth: true } : {})}
                  label="Property Company (Optional)"
                  name="cShipCompany"
                  value={formData.cShipCompany || ''}
                  onChange={handleChange}
                  error={!!errors.cShipCompany}
                  helperText={errors.cShipCompany}
                  size={useSize}
                  sx={textFieldStyle}
                  ref={registerField('cShipCompany')}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <BusinessIcon fontSize="small" />
                      </InputAdornment>
                    ),
                  }}
                />
              </Box>
            </Grid>
            <Grid item xs={12}>
              <Box className="field-wrapper" sx={{ width: '100%' }}>
                <TextField
                  {... (fullWidth ? { fullWidth: true } : {})}
                  label="Property Street Address"
                  name="cShipAddress1"
                  value={formData.cShipAddress1}
                  onChange={handleChange}
                  error={!!errors.cShipAddress1}
                  helperText={errors.cShipAddress1}
                  size={useSize}
                  sx={textFieldStyle}
                  ref={registerField('cShipAddress1')}
                  required
                />
              </Box>
            </Grid>
            <Grid item xs={12}>
              <Box className="field-wrapper" sx={{ width: '100%' }}>
                <TextField
                  {... (fullWidth ? { fullWidth: true } : {})}
                  label="Property Address Line 2 (Optional)"
                  name="cShipAddress2"
                  value={formData.cShipAddress2 || ''}
                  onChange={handleChange}
                  error={!!errors.cShipAddress2}
                  helperText={errors.cShipAddress2}
                  size={useSize}
                  sx={textFieldStyle}
                  ref={registerField('cShipAddress2')}
                />
              </Box>
            </Grid>
            <Grid item xs={12}>
              <Box className="field-wrapper" sx={{ width: '100%' }}>
                <TextField
                  {... (fullWidth ? { fullWidth: true } : {})}
                  label="Property City"
                  name="cShipCity"
                  value={formData.cShipCity}
                  onChange={handleChange}
                  error={!!errors.cShipCity}
                  helperText={errors.cShipCity}
                  size={useSize}
                  sx={textFieldStyle}
                  ref={registerField('cShipCity')}
                  required
                />
              </Box>
            </Grid>
            <Grid item xs={12}>
              <Box className="field-wrapper" sx={{ width: '100%' }}>
                <TextField
                  {... (fullWidth ? { fullWidth: true } : {})}
                  select
                  label="Property State"
                  name="cShipState"
                  value={formData.cShipState}
                  onChange={handleChange}
                  error={!!errors.cShipState}
                  helperText={errors.cShipState}
                  size={useSize}
                  sx={textFieldStyle}
                  ref={registerField('cShipState')}
                  required
                >
                  {STATES.map((state) => (
                    <MenuItem key={state} value={state}>
                      {state}
                    </MenuItem>
                  ))}
                </TextField>
              </Box>
            </Grid>
            <Grid item xs={12}>
              <Box className="field-wrapper" sx={{ width: '100%' }}>
                <TextField
                  {... (fullWidth ? { fullWidth: true } : {})}
                  label="Property ZIP"
                  name="cShipZip"
                  value={formData.cShipZip}
                  onChange={handleChange}
                  error={!!errors.cShipZip}
                  helperText={errors.cShipZip}
                  size={useSize}
                  sx={textFieldStyle}
                  ref={registerField('cShipZip')}
                  required
                />
              </Box>
            </Grid>
            <Grid item xs={12}>
              <Box className="field-wrapper" sx={{ width: '100%' }}>
                <TextField
                  {... (fullWidth ? { fullWidth: true } : {})}
                  label="Property County (Optional)"
                  name="ship_county"
                  value={formData.ship_county || ''}
                  onChange={handleChange}
                  error={!!errors.ship_county}
                  helperText={errors.ship_county}
                  size={useSize}
                  sx={textFieldStyle}
                  ref={registerField('ship_county')}
                />
              </Box>
            </Grid>
            <Grid item xs={12}>
              <Box className="field-wrapper" sx={{ width: '100%' }}>
                <TextField
                  {... (fullWidth ? { fullWidth: true } : {})}
                  select
                  label="Property Country"
                  name="cShipCountry"
                  value={formData.cShipCountry}
                  onChange={handleChange}
                  error={!!errors.cShipCountry}
                  helperText={errors.cShipCountry}
                  size={useSize}
                  sx={textFieldStyle}
                  ref={registerField('cShipCountry')}
                  required
                >
                  {COUNTRIES.map((country) => (
                    <MenuItem key={country} value={country}>
                      {country}
                    </MenuItem>
                  ))}
                </TextField>
              </Box>
            </Grid>
          </>
        )}
      </Grid>
    </Box>
  );
};

export default PropertySection;